/*
这是一个用链表实现的栈,该栈接受的类型需要修改头文件
所有出栈入栈的数据需要先进行空指针检查 ,不能使用非指针类型
*/

#include "link_stack_simple.h"
#include <stdlib.h>

// 链表中的节点类型定义
struct node {
  Item data;
  struct node *next;
};

// 定义头文件中的不完整类型
struct stack_t {
  struct node *top;
  size_t size;
};

cstack stack_create(void) {
  cstack s;
  if ((s = malloc(sizeof(struct stack_t))) == NULL)
    return NULL;

  if ((s->top = malloc(sizeof(struct node))) == NULL) {
    free(s);
    return NULL;
  }

  s->size = 0;
  return s;
}

bool stack_push(cstack s, Item data) {
  struct node *new_node = malloc(sizeof(struct node));
  if (new_node == NULL)
    return false;

  new_node->data = data;
  new_node->next = s->top;
  s->top = new_node;
  ++s->size;

  return true;
}

Item stack_pop(cstack s) {
  if (stack_is_empty(s))
    return NULL;

  struct node *top = s->top;
  Item p_ret = top->data;
  s->top = top->next;
  free(top);
  --s->size;

  return p_ret;
}

Item stack_peek(cstack s) { return stack_is_empty(s) ? NULL : s->top->data; }

void stack_clear(cstack s) {
  while (!stack_is_empty(s))
    stack_pop(s);
}

void stack_destory(cstack s) {
  stack_clear(s);
  free(s->top);
  free(s);
}

bool stack_is_empty(cstack s) { return s->size == 0; }

bool stack_is_full(cstack s) { return false; }
